package com.djinfo.work.common.dao.impl;

import com.djinfo.work.common.dao.BaseDao;
import org.hibernate.*;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * 整合后的BASEDAO
 * @author ChenShun
 *
 */
@SuppressWarnings("rawtypes")
@Repository("BaseDaoI")
public class BaseDaoImpl extends HibernateTemplate implements BaseDao {

	@Resource(name = "sessionFactory")
	public SessionFactory sessionFactory;
	@PostConstruct
	public void session(){
		super.setSessionFactory(sessionFactory);
	}

	/**
	 * 绑定参数
	 *
	 * @param query
	 * @param objects
	 *
	 */
	private void bindingParameter(Query query, Object... objects) {
		for (int i = 0; i < objects.length; i++) {

			query.setParameter(i, objects[i]);
		}

	}

	/**
	 * 保存
	 * @param entity
	 */
	public void save(Serializable entity, boolean autoCommit){
		Session mySession = super.getSessionFactory().getCurrentSession();
		mySession.setFlushMode(FlushMode.COMMIT);
		if (autoCommit) {
			Transaction trans = mySession.beginTransaction();
			try{
				super.save(entity);
				trans.commit();
			} catch(Exception e){
				e.printStackTrace();
				trans.rollback();
			}
			mySession.flush();
		} else {
			super.save(entity);
		}
	}

	/**
	 * 保存
	 * @param entity
	 */
	public void savetwo(Serializable entity){
		super.save(entity);
	}
	/**
	 * 保存
	 * @param entity
	 */
	public void save(Serializable entity){
		Session mySession = super.getSessionFactory().getCurrentSession();
		mySession.setFlushMode(FlushMode.COMMIT);
		super.save(entity);

	}
	/**
	 * 保存
	 * @param entity
	 */
	public void update(Serializable entity){
		// TODO Auto-generated method stub
//		Session mySession = super.getSessionFactory().getCurrentSession();
//		Transaction trans = mySession.beginTransaction();
//		try{
		super.update(entity);
//			trans.commit();
//		}
//		catch(Exception e){
//			trans.rollback();
//		}
//		mySession.flush();
	}
	/**
	 * 保存
	 */
	public int updateSql(String hql, Object... objects){
		// TODO Auto-generated method stub
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createSQLQuery(hql);
		this.bindingParameter(query, objects);
		return query.executeUpdate();
	}
	/**
	 * 删除
	 * @param entity
	 */
	public void delete(Serializable entity) {
		Session mySession = super.getSessionFactory().getCurrentSession();
//		Transaction trans = mySession.beginTransaction();
		mySession.delete(entity);
//		try{
//			trans.commit();
//		}
//		catch(Exception e){
//			trans.rollback();
//		}
		mySession.flush();
	}
	/**
	 * 根据HQL进行批量update与delete
	 * @param hql
	 * @param objects
	 * @return
	 */
	public int updateByHQL(String hql, Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		this.bindingParameter(query, objects);
		return query.executeUpdate();
	}



	/**
	 * 根据HQL查询单个对象
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public Object getUniqueObject(String hql, Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		return query.uniqueResult();
	}
	/**
	 * 根据sql查询单个对象
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public Object getUniqueObjectSql(String hql,Class clz, Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createSQLQuery(hql).setResultTransformer(Transformers.aliasToBean(clz));
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		return query.uniqueResult();
	}
	/**
	 * 根据HQL查询单个对象
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public Object getUniqueObjectOne(String hql, Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		return query.setMaxResults(1).uniqueResult();
	}
	/**
	 * 根据HQL进行查询
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public List getList(String hql,
						Object... objects) {

		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			ThreadLocal threadLocal=new ThreadLocal();
			threadLocal.set(sessionFactory);

			threadLocal.get();
			this.bindingParameter(query, objects);
		}
		return query.list();
	}

	/**
	 * 根据sql进行查询
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public List getListSql(String hql,Class clz,
						Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createSQLQuery(hql).setResultTransformer(Transformers.aliasToBean(clz));
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		return query.list();
	}
	/**
	 * 根据HQL进行查询
	 *
	 * @param hql
	 * @param objects
	 * @return
	 */
	public List getListMax(String hql,
						   Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		query.setMaxResults(10);
		return query.list();
	}
	/**
	 * 根据HQL进行分页查询
	 *
	 * @param hql
	 * @param pageNum
	 * @param pageSize
	 * @param objects
	 * @return
	 */
	public List pageQuery(String hql, Integer pageNum, Integer pageSize,
						  Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		if (pageNum != null && pageSize != null) {
			query.setFirstResult((pageNum - 1) * pageSize).setMaxResults(
					pageSize);
		}
		return query.list();
	}

	/**
	 * 根据HQL进行分页查询
	 *
	 * @param pageNum
	 * @param pageSize
	 * @param objects
	 * @return
	 */
	public List pageQueryBySQL(String sql, Integer pageNum, Integer pageSize,
							   Object... objects) {
		SQLQuery query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createSQLQuery(sql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		if (pageNum != null && pageSize != null) {
			query.setFirstResult((pageNum - 1) * pageSize).setMaxResults(
					pageSize);
		}
		return query.list();
	}
	/**
	 * 根据HQL进行分页查询
	 *
	 * @param pageNum
	 * @param pageSize
	 * @param objects
	 * @return
	 */
	public List pageQuerySQL(String sql, Integer pageNum, Integer pageSize,
							   Object... objects) {
		SQLQuery query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createSQLQuery(sql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		if (pageNum != null && pageSize != null) {
			query.setFirstResult(pageNum).setMaxResults(
					pageSize);
		}
		return query.list();
	}

	/**
	 * 根据HQL进行分页查询
	 *
	 * @param hql
	 * @param pageNum
	 * @param pageSize
	 * @param objects
	 * @return
	 */
	public List page(String hql, Integer pageNum, Integer pageSize,
					 Object... objects) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
		if(objects != null){
			this.bindingParameter(query, objects);
		}
		if (pageNum != null && pageSize != null) {
			query.setFirstResult(pageNum).setMaxResults(
					pageSize);
		}
		return query.list();
	}

	@Override
	public List getList(String hql, List<String> list) {
		Query query =super.getSessionFactory().getCurrentSession().createQuery(hql);

		query.setParameterList("name",list);





		return null;
	}

	/**
	 * for循环
	 * @param list
	 * @return
	 */
	public Integer []  getforInteger(List list){
		Integer[] ints =new Integer[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ints[i] =Integer.parseInt( list.get(i).toString());
		}
		return ints;
	}


	/**
	 * 通过主键获取记录
	 * @param object
	 * @param pkID
	 * @return
	 */
	public Object getByPrimaryKey(Class object, String pkID){
		return super.getSessionFactory().getCurrentSession().get(object, pkID);
	}

	public <T> T getEntity(Class entityName, Serializable id) {
		Session mySession = super.getSessionFactory().getCurrentSession();
		T t = (T) mySession.get(entityName, id);
		if (t != null) {
			mySession.flush();
		}
		return t;
	}

	public <T> List<T> loadAll(final Class<T> entityClass) {
		Session mySession = super.getSessionFactory().getCurrentSession();
		Criteria criteria = mySession.createCriteria(entityClass);
		return criteria.list();
	}

	@Override
	public <T> void saveList(List<T> list) {
		Session session = super.getSessionFactory().getCurrentSession();
		if (list != null && list.size() > 0) {
			try {
				T t = null; // 创建药品对象
				for (int i = 0; i < list.size(); i++) {
					t = (T) list.get(i); // 获取药品
					session.save(t); // 保存药品对象
					// 批插入的对象立即写入数据库并释放内存
				}
			} catch (Exception e) {
				e.printStackTrace(); // 打印错误信息
				session.getTransaction().rollback(); // 出错将回滚事物
			} finally {
			}
		}
	}

	/**
	 * 创建Criteria对象带属性比较
	 *
	 * @param <T>
	 * @param entityClass
	 * @param criterions
	 * @return
	 */
	private <T> Criteria createCriteria(Class<T> entityClass,
										Criterion... criterions) {
		Session session = super.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(entityClass);
		for (Criterion c : criterions) {
			criteria.add(c);
		}
		return criteria;
	}

	@Override
	public <T> T findUniqueByProperty(Class<T> entityClass, String propertyName, Object value) {
		Assert.hasText(propertyName);
		return (T) createCriteria(entityClass,
				Restrictions.eq(propertyName, value)).uniqueResult();
	}

	@Override
	public <T> List<T> findByProperty(Class<T> entityClass, String propertyName, Object value) {
		Assert.hasText(propertyName);
		return (List<T>) createCriteria(entityClass,
				Restrictions.eq(propertyName, value)).list();
	}

	public void updateBySqlString(final String query) {
		Session mySession = super.getSessionFactory().getCurrentSession();
		Query querys = mySession.createSQLQuery(query);
		querys.executeUpdate();
	}

	public void delSome(String hql) {
		Query query = ((SessionFactory) super.getSessionFactory()).getCurrentSession().createQuery(hql);
//		this.bindingParameter(query, objects);
		query.executeUpdate();
	}

	/*@Override
	public <T> void saveList(List<T> list) {
		Session session = null;
		if (list != null && list.size() > 0) {
			try {
				session = super.getSessionFactory().getCurrentSession(); // 获取Session
				//session.beginTransaction(); // 开启事物
				T t = null; // 创建药品对象
				// 循环获取药品对象
				for (int i = 0; i < list.size(); i++) {
					t = (T) list.get(i); // 获取药品
					session.save(t); // 保存药品对象
					// 批插入的对象立即写入数据库并释放内存
					if (i % 30 == 0) {
						session.flush();
						session.clear();
					}
				}
				//session.getTransaction().commit(); // 提交事物
			} catch (Exception e) {
				e.printStackTrace(); // 打印错误信息
				session.getTransaction().rollback(); // 出错将回滚事物
			} finally {
				session.close();
			}
		}
	}*/


	/*public <T extends Serializable> void saveList2(List<T> list) {
		Session session = null;
		if (list != null && list.size() > 0) {
			try {
				session = super.getSessionFactory().getCurrentSession(); // 获取Session
				session.beginTransaction(); // 开启事物
				T t = null; // 创建药品对象
				// 循环获取药品对象
				for (int i = 0; i < list.size(); i++) {
					t = (T) list.get(i); // 获取药品
					session.save(t); // 保存药品对象
					// 批插入的对象立即写入数据库并释放内存
					if (i % 30 == 0) {
						session.flush();
						session.clear();
					}
				}
				session.getTransaction().commit(); // 提交事物
			} catch (Exception e) {
				e.printStackTrace(); // 打印错误信息
				session.getTransaction().rollback(); // 出错将回滚事物
			} finally {
				session.close();
			}
		}
	}*/
}
